import { fileURLToPath, URL } from 'node:url'
import os from 'node:os';
import vue from '@vitejs/plugin-vue'
import autoprefixer from 'autoprefixer'
import tailwind from 'tailwindcss'
import { defineConfig } from 'vite'

import vueJsx from '@vitejs/plugin-vue-jsx';
import ElementPlus from 'unplugin-element-plus/vite';
import Icons from 'unplugin-icons/vite';
import monacoEditorPlugin, {
  type IMonacoEditorOpts,
} from 'vite-plugin-monaco-editor';
import optimizer from 'vite-plugin-optimizer';

function getNetworkIp(ver = 4) {
  const osType = os.type(); // 系统类型
  const netInfo = os.networkInterfaces();
  let ip = '';
  if (osType === 'Windows_NT') {
    for (const dev in netInfo) {
      // win7的网络信息中显示为本地连接，win10显示为以太网
      if ((dev === '本地连接' || dev === '以太网') && netInfo[dev]) {
        for (let j = 0; j < netInfo[dev].length; j++) {
          if (
            netInfo[dev] &&
            netInfo[dev][j] &&
            netInfo[dev][j]?.family === `IPv${ver}`
          ) {
            ip = netInfo[dev][j]?.address || 'localhost';
            break;
          }
        }
      }
    }
  } else if (osType === 'Linux') {
    const eth0 = netInfo.eth0 ? netInfo.eth0[0] : { address: 'localhost' };
    ip = (eth0 as os.NetworkInterfaceInfo).address || 'localhost';
  }
  return ip;
}
const monacoEditorPluginDefault = (monacoEditorPlugin as any).default as (
  options: IMonacoEditorOpts,
) => any;

// https://vite.dev/config/
export default defineConfig({
  css: {
    preprocessorOptions: {
      scss: {
        api: 'modern-compiler', // or 'modern'
      },
    },
    postcss: {
      plugins: [tailwind(), autoprefixer()],
    },
  },
  plugins: [vue(),
  vueJsx(),
  ElementPlus({
    format: 'esm',
  }),
  monacoEditorPluginDefault({
    languageWorkers: [
      'css',
      'html',
      'json',
      'typescript',
      'editorWorkerService',
    ],
  }),
  optimizer({
    child_process: () => ({
      code: `const child_process = import.meta.glob('child_process'); export { child_process as default }`,
      find: /^(node:)?child_process$/,
    }),
  }),
  Icons({}),],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  server: {
    proxy: {
      '/data': {
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/data/, ''),
        // 启动terminal服务地址
        target: 'http://localhost:801/',
        ws: true,
      },
      '/wos-server': {
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/wos-server/, ''),
        // 启动terminal服务地址
        target: `http://${getNetworkIp()}:4000/`,
        ws: true,
      },
      '/ws-server': {
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/ws-server/, ''),
        // 启动terminal服务地址
        target: `http://${getNetworkIp()}:4000/`,
        ws: true,
      },
    },
  },
})
